<template>
  <a-modal
    v-model:open="modalOpen"
    title="编辑用户信息"
    :width="600"
    :closable="true"
    :mask-closable="true"
    :mask="true"
    :z-index="1000"
    :centered="true"
    @cancel="handleCancel"
    @ok="handleCancel"
  >
    <div class="profile-edit-container">
      <!-- 头像上传 -->
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <a-avatar 
            :src="getMinioFileUrl(avatarUrl || userInfo?.filePath) || 'https://via.placeholder.com/100x100'" 
            :size="100"
            class="user-avatar"
          />
          <div class="avatar-upload-overlay" @click="triggerFileUpload">
            <CameraOutlined class="upload-icon" />
            <span>更换头像</span>
          </div>
        </div>
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleFileChange"
        />
        <div class="avatar-tips">
          <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
        </div>
      </div>

      <!-- 用户信息表单 -->
      <a-form
        :model="formData"
        :rules="rules"
        @finish="handleSubmit"
        class="profile-form"
        layout="vertical"
      >
        <a-form-item label="用户名" name="username">
          <a-input
            v-model:value="formData.username"
            size="large"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="昵称" name="nickname">
          <a-input
            v-model:value="formData.nickname"
            size="large"
            placeholder="请输入昵称"
          >
            <template #prefix>
              <SmileOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="邮箱" name="email">
          <a-input
            v-model:value="formData.email"
            size="large"
            placeholder="请输入邮箱地址"
          >
            <template #prefix>
              <MailOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="性别" name="sex">
          <a-radio-group v-model:value="formData.sex">
            <a-radio :value="0">
              <ManOutlined style="color: #1890ff" />
              男
            </a-radio>
            <a-radio :value="1">
              <WomanOutlined style="color: #eb2f96" />
              女
            </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="手机号" name="phone">
          <a-input
            v-model:value="formData.phone"
            size="large"
            placeholder="请输入手机号"
          >
            <template #prefix>
              <PhoneOutlined />
            </template>
          </a-input>
          <template #extra>
            <span class="privacy-tip">手机号仅用于账号安全验证，不会公开显示</span>
          </template>
        </a-form-item>

        <!-- 保存按钮 -->
        <a-form-item>
          <a-button
            type="primary"
            size="large"
            block
            class="save-btn"
            @click="handleSubmit"
            :loading="submitting"
          >
            保存修改
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { updateUser } from '@/api/user/sysUserController'
import { uploadPic } from '@/api/media/bizFilesController'
import {
  UserOutlined,
  MailOutlined,
  PhoneOutlined,
  CameraOutlined,
  ManOutlined,
  WomanOutlined,
  SmileOutlined
} from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/authStore'

// 获取MinIO文件完整URL的工具函数
const getMinioFileUrl = (filePath?: string): string => {
  if (!filePath) {
    return 'https://via.placeholder.com/100x100'
  }
  
  // 如果已经是完整URL，直接返回
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath
  }
  
  // 否则拼接MinIO基础URL
  const minioUrl = import.meta.env.VITE_MINIO_URL || 'http://172.172.2.99:9000'
  return `${minioUrl}${filePath}`
}

interface UserInfo {
  userId?: number
  username?: string
  nickname?: string
  email?: string
  sex?: number
  phone?: string
  filePath?: string
}

interface Props {
  open: boolean
  userInfo?: any
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'profile-updated', user: any): void
}

const props = withDefaults(defineProps<Props>(), {
  userInfo: () => ({})
})

const emit = defineEmits<{
  'profile-updated': [userInfo: UserInfo]
  'update:open': [value: boolean]
}>()

const authStore = useAuthStore()

// 计算属性用于v-model:open
const modalOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value)
})

// 表单数据
const formData = reactive({
  username: '',
  nickname: '',
  email: '',
  sex: 0,
  phone: ''
})

// 头像相关
const avatarUrl = ref('')
const fileInput = ref<HTMLInputElement>()

// 状态
const submitting = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2-20个字符之间', trigger: 'blur' }
  ],
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (props.userInfo) {
    formData.username = props.userInfo.username || ''
    formData.nickname = props.userInfo.nickname || ''
    formData.email = props.userInfo.email || ''
    formData.sex = props.userInfo.sex || 0
    formData.phone = props.userInfo.phone || ''
  }
}

// 触发文件上传
const triggerFileUpload = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 文件大小检查（2MB）
  if (file.size > 2 * 1024 * 1024) {
    message.error('文件大小不能超过2MB')
    return
  }
  
  // 文件类型检查
  if (!file.type.startsWith('image/')) {
    message.error('请选择图片文件')
    return
  }
  
  try {
    submitting.value = true
    
    // 直接使用成功的上传方式
    const response = await uploadPic({}, file)
    
    if ((response as any).code === '00000' && (response as any).data) {
      const filePath = (response as any).data.previewUrl
      avatarUrl.value = filePath
      
      // 更新用户头像信息
      await updateUser({
        userId: props.userInfo?.userId,
        filePath: filePath
      })
      
      message.success('头像上传成功！')
      
      emit('profile-updated', { 
        ...props.userInfo, 
        filePath: filePath
      })
      
      // 同时更新authStore中的用户信息
      authStore.updateUserInfo({
        filePath: filePath
      })
      
      console.log('头像上传成功，MinIO地址:', filePath)
    } else {
      throw new Error((response as any).message || '头像上传失败')
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    const errMsg = error instanceof Error ? error.message : '头像上传失败'
    message.error(errMsg)
  } finally {
    submitting.value = false
    // 清空文件输入
    if (target) target.value = ''
  }
}

// 处理表单提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true
    
    // 调用更新用户信息API
    const result = await updateUser({
      userId: props.userInfo?.userId,
      username: formData.username,
      nickname: formData.nickname,
      email: formData.email,
      sex: formData.sex,
      phone: formData.phone
    } as any)
    
    if ((result as any).code === '00000') {
      message.success('用户信息更新成功！')
      emit('profile-updated', {
        ...props.userInfo,
        username: formData.username,
        nickname: formData.nickname,
        email: formData.email,
        sex: formData.sex,
        phone: formData.phone
      })
      handleCancel()
    } else {
      throw new Error((result as any).msg || '更新失败')
    }
    
  } catch (error: any) {
    if (error.errorFields) {
      // 表单验证错误，不需要处理
      return
    }
    message.error(error.message || '更新失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('update:open', false)
}

// 表单引用
const formRef = ref()

// 组件挂载时初始化数据
onMounted(() => {
  initFormData()
})

// 监听用户信息变化
watch(() => props.userInfo, () => {
  initFormData()
}, { immediate: true })
</script>

<style scoped>
.profile-edit-container {
  padding: 20px 0;
}

.avatar-section {
  text-align: center;
  margin-bottom: 24px;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.user-avatar {
  border: 3px solid #f0f0f0;
  transition: all 0.3s;
}

.avatar-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .avatar-upload-overlay {
  opacity: 1;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.avatar-tips {
  color: #666;
  font-size: 12px;
}

.avatar-tips p {
  margin: 0;
}

.profile-form {
  margin-bottom: 24px;
}

.save-btn {
  height: 40px;
  font-size: 16px;
  font-weight: 500;
}

.privacy-tip {
  color: #999;
  font-size: 12px;
}
</style>
